package com.xinyuan.plug;

import com.xinyuan.plug.generator.DaoGenerator;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Mojo(name = "generate-dao")
public class DaoGeneratorMojo extends AbstractMojo {
    @Parameter(property = "generate-dao.entityPackages", required = true)
    private List<String> entityPackages;

    @Parameter(property = "generate-dao.excludeClasses")
    private List<String> excludeClasses;

    @Parameter(property = "generate-dao.outputDir", defaultValue = "${project.build.directory}/generated-sources/dao")
    private String outputDir;

    @Parameter(property = "generate-dao.daoPackage", required = true)
    private String daoPackage;

    @Parameter(property = "generate-dao.tablePrefix", defaultValue = "")
    private String tablePrefix;

    @Parameter(property = "generate-dao.overwrite", defaultValue = "false")
    private boolean overwrite;

    @Parameter(property = "generate-dao.commonFields")
    private Map<String, String> commonFields;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("Starting DAO and Wrapper file generation...");
        getLog().info("Entity packages: " + entityPackages);
        getLog().info("Excluded classes: " + excludeClasses);
        getLog().info("Output directory: " + outputDir);
        getLog().info("DAO package: " + daoPackage);
        getLog().info("Table prefix: " + tablePrefix);
        getLog().info("commonFields: " + (commonFields != null ? Arrays.toString(commonFields.values().toArray()) : null));

        try {
            DaoGenerator generator = new DaoGenerator();
            generator.setEntityPackages(entityPackages);
            generator.setExcludeClasses(excludeClasses);
            generator.setOutputDir(new File(outputDir));
            generator.setDaoPackage(daoPackage);
            generator.setTablePrefix(tablePrefix);
            generator.setOverwrite(overwrite);
            generator.setCommonFields(commonFields);
            generator.setLog(getLog());

            generator.generate();

            getLog().info("DAO interfaces and Wrapper files generated successfully!");
        } catch (Exception e) {
            getLog().error("Generation failed: " + e.getMessage(), e);
            throw new MojoExecutionException("DAO generation failed", e);
        }
    }
}
